package com.douyin.controller;

import com.douyin.common.Result;
import com.douyin.entity.ParseRecord;
import com.douyin.entity.User;
import com.douyin.service.DouyinParseService;
import com.douyin.service.ParseRecordService;
import com.douyin.service.UserService;
import com.douyin.util.JwtUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import jakarta.servlet.http.HttpServletRequest;
import java.util.Map;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

@Slf4j
@RestController
@RequestMapping("/user")
@RequiredArgsConstructor
public class UserController {

    private final DouyinParseService douyinParseService;
    private final ParseRecordService parseRecordService;
    private final UserService userService;
    private final JwtUtil jwtUtil;
    private final RestTemplate restTemplate;

    @PostMapping("/login")
    public Result<?> login(@RequestBody Map<String, String> request) {
        String openid = request.get("openid");
        String nickname = request.get("nickname");
        String avatarUrl = request.get("avatarUrl");

        if (openid == null || openid.trim().isEmpty()) {
            return Result.error("openid不能为空");
        }

        try {
            User user = userService.createOrUpdateUser(openid, nickname, avatarUrl);
            String token = jwtUtil.generateToken(user.getId().toString(), "user");

            return Result.success("登录成功", Map.of(
                "token", token,
                "user", user
            ));
        } catch (Exception e) {
            log.error("用户登录失败", e);
            return Result.error("登录失败");
        }
    }

    @PostMapping("/wx-login")
    public Result<?> wxLogin(@RequestBody Map<String, String> request) {
        String code = request.get("code");
        String nickname = request.get("nickname");
        String avatarUrl = request.get("avatarUrl");

        if (code == null || code.trim().isEmpty()) {
            return Result.error("code不能为空");
        }

        try {
            String openid;

            // 测试模式：如果是测试code，生成模拟openid
            if (code.startsWith("test")) {
                openid = "test_openid_" + System.currentTimeMillis();
                log.info("使用测试模式，生成openid: {}", openid);
            } else {
                // 正式模式：调用微信API获取openid
                openid = getOpenidFromWechat(code);
                if (openid == null) {
                    return Result.error("获取微信用户信息失败");
                }
            }

            User user = userService.createOrUpdateUser(openid, nickname, avatarUrl);
            String token = jwtUtil.generateToken(user.getId().toString(), "user");

            return Result.success("登录成功", Map.of(
                "token", token,
                "user", user
            ));
        } catch (Exception e) {
            log.error("微信登录失败", e);
            return Result.error("登录失败");
        }
    }

    @GetMapping("/profile")
    public Result<?> getUserProfile(HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        if (token == null || !token.startsWith("Bearer ")) {
            return Result.unauthorized();
        }

        token = token.substring(7);
        if (!jwtUtil.validateToken(token)) {
            return Result.unauthorized();
        }

        String userIdStr = jwtUtil.getSubjectFromToken(token);
        Long userId = Long.parseLong(userIdStr);

        try {
            User user = userService.findById(userId);
            if (user == null) {
                return Result.error("用户不存在");
            }

            long todayCount = parseRecordService.getTodayParseCount(userId);
            long totalCount = parseRecordService.getTotalParseCount(userId);

            return Result.success(Map.of(
                "user", user,
                "todayCount", todayCount,
                "totalCount", totalCount
            ));
        } catch (Exception e) {
            log.error("获取用户档案失败", e);
            return Result.error("获取用户信息失败");
        }
    }

    @PostMapping("/update-profile")
    public Result<?> updateProfile(@RequestBody Map<String, String> request,
                                  HttpServletRequest httpRequest) {
        String token = httpRequest.getHeader("Authorization");
        if (token == null || !token.startsWith("Bearer ")) {
            return Result.unauthorized();
        }

        token = token.substring(7);
        if (!jwtUtil.validateToken(token)) {
            return Result.unauthorized();
        }

        String userIdStr = jwtUtil.getSubjectFromToken(token);
        Long userId = Long.parseLong(userIdStr);

        String nickname = request.get("nickname");
        String avatarUrl = request.get("avatarUrl");

        try {
            User user = userService.updateUserProfile(userId, nickname, avatarUrl);
            return Result.success("更新成功", user);
        } catch (Exception e) {
            log.error("更新用户档案失败", e);
            return Result.error("更新失败");
        }
    }

    @PostMapping("/parse")
    public Result<?> parseDouyinUrl(@RequestBody Map<String, String> request,
                                   HttpServletRequest httpRequest) {
        String url = request.get("url");
        String token = httpRequest.getHeader("Authorization");

        if (url == null || url.trim().isEmpty()) {
            return Result.error("链接不能为空");
        }

        if (token == null || !token.startsWith("Bearer ")) {
            return Result.unauthorized();
        }

        token = token.substring(7);
        if (!jwtUtil.validateToken(token)) {
            return Result.unauthorized();
        }

        String userIdStr = jwtUtil.getSubjectFromToken(token);
        Long userId = Long.parseLong(userIdStr);

        if (!userService.isUserActive(userId)) {
            return Result.error("用户已被禁用");
        }

        if (!douyinParseService.isValidDouyinUrl(url)) {
            return Result.error("请输入有效的抖音链接");
        }

        long todayCount = parseRecordService.getTodayParseCount(userId);
        if (todayCount >= 100) {
            return Result.error("今日解析次数已达上限");
        }

        try {
            String userIp = getClientIpAddress(httpRequest);
            String userAgent = httpRequest.getHeader("User-Agent");

            ParseRecord record = parseRecordService.createParseRecord(userId, url, userIp, userAgent, "miniprogram");

            long startTime = System.currentTimeMillis();
            Map<String, Object> parseResult = douyinParseService.parseDouyinUrl(url);
            int parseTime = (int) (System.currentTimeMillis() - startTime);

            parseRecordService.updateParseResult(record.getId(), parseResult, parseTime);

            if ((Boolean) parseResult.get("success")) {
                userService.incrementParseCount(userId);
            }

            return Result.success(parseResult);

        } catch (Exception e) {
            log.error("解析失败", e);
            return Result.error("解析失败，请稍后重试");
        }
    }

    @GetMapping("/records")
    public Result<?> getMyRecords(@RequestParam(defaultValue = "1") int page,
                                 @RequestParam(defaultValue = "10") int size,
                                 HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        if (token == null || !token.startsWith("Bearer ")) {
            return Result.unauthorized();
        }

        token = token.substring(7);
        if (!jwtUtil.validateToken(token)) {
            return Result.unauthorized();
        }

        String userIdStr = jwtUtil.getSubjectFromToken(token);
        Long userId = Long.parseLong(userIdStr);

        var records = parseRecordService.getParseRecords(page, size, userId, null, null, null, null, null, null);
        return Result.success(records);
    }

    private String getOpenidFromWechat(String code) {
        try {
            String appId = "wx2ce4d7a134337c3d";
            String appSecret = "b4002a0b47629765cbc87b6b12bb1c91";
            String url = String.format(
                "https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code",
                appId, appSecret, code
            );

            // 微信API有时返回text/plain，我们先获取字符串，再解析JSON
            ResponseEntity<String> response = restTemplate.getForEntity(url, String.class);
            String responseBody = response.getBody();

            if (responseBody != null) {
                // 手动解析JSON字符串
                if (responseBody.contains("\"openid\"")) {
                    // 简单的字符串提取openid（生产环境建议使用JSON库）
                    String[] parts = responseBody.split("\"openid\":\"");
                    if (parts.length > 1) {
                        String openidPart = parts[1];
                        int endIndex = openidPart.indexOf("\"");
                        if (endIndex > 0) {
                            return openidPart.substring(0, endIndex);
                        }
                    }
                }
                log.error("微信API返回错误: {}", responseBody);
                return null;
            } else {
                log.error("微信API返回空响应");
                return null;
            }
        } catch (Exception e) {
            log.error("调用微信API失败", e);
            return null;
        }
    }

    private String getClientIpAddress(HttpServletRequest request) {
        String xForwardedFor = request.getHeader("X-Forwarded-For");
        if (xForwardedFor != null && !xForwardedFor.isEmpty()) {
            return xForwardedFor.split(",")[0].trim();
        }

        String xRealIp = request.getHeader("X-Real-IP");
        if (xRealIp != null && !xRealIp.isEmpty()) {
            return xRealIp;
        }

        return request.getRemoteAddr();
    }
}
